<template>
  <div class="merge-container">
    <el-dialog
      ref="mergeDialog"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      :append-to-body="false"
      :modal-append-to-body="false"
      :class="{'mobile-el-dialog': showMobilePage}"
      class="merge-resource-dialog"
      width="1000px">
      <!-- <el-scrollbar class="merge-resource-scrollbar"> -->
      <div class="main">
        <div :class="{'is-mobile': showMobilePage}" class="merge-header">
          <div style="margin-right: 10px;flex:1">
            <Title title="合并资源" font-size="16px">
              <span v-if="!showMobilePage" class="right-tip">选中需要合并的资源，且选择合并源</span>
            </Title>
          </div>
          <div :class="{'mt10': showMobilePage}" style="display:flex;align-items:center;">
            <el-input v-model="keyword" class="merge-input" type="text" placeholder="请输入内容" @keyup.enter.native="getData(true)">
              <el-select slot="prepend" v-model="filedName" popper-class="global-select-down" placeholder="请选择" class="changeStatus">
                <el-option
                  v-for="item in keyOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"/>
              </el-select>
            </el-input>
            <el-button class="search-btn-style search-btn" type="primary" size="small" @click="getData(true)"><i class="el-icon-search"/></el-button>
          </div>
        </div>
        <div class="merge-table">
          <el-table
            v-loading="loading"
            ref="mergeTable"
            :data="mergeData.items"
            row-class-name="merge-table-row"
            max-height="400px"
            empty-text="暂无数据"
            header-cell-class-name="order-data-header-cell"
            fit
          >
            <el-table-column :fixed="!showMobilePage" align="left" label="选中" min-width="50">
              <template slot-scope="scope">
                <el-checkbox-group v-model="scope.row.ids" @change="selectItem($event, scope.row)">
                  <div v-for="(item,index) in scope.row.children" :key="index" :class="{'row-selected':isSelect(scope.row.ids, item.mediumId)}" style="justify-content:center;" class="merge-row-item">
                    <el-checkbox :label="item.mediumId" />
                  </div>
                </el-checkbox-group>
              </template>
            </el-table-column>
            <el-table-column :fixed="!showMobilePage" align="center" label="合并源" min-width="70">
              <template slot-scope="scope">
                <el-radio-group v-model="scope.row.mainId" style="width: 100%;">
                  <div v-for="(item,index) in scope.row.children" :key="index" :class="{'row-selected':isSelect(scope.row.ids, item.mediumId)}" style="justify-content:center;" class="merge-row-item">
                    <el-radio :disabled="scope.row.ids.length < 2 || !isSelect(scope.row.ids, item.mediumId)" :label="item.mediumId"/>
                  </div>
                </el-radio-group>
              </template>
            </el-table-column>
            <el-table-column :fixed="!showMobilePage" align="left" label="账号" min-width="110">
              <template slot-scope="scope">
                <div v-for="(item,index) in scope.row.children" :style="rowStyle(item)" :key="index" :class="{'row-selected':isSelect(scope.row.ids, item.mediumId)}" class="merge-row-item">
                  <ToolTip :content="item.resourceName" class="resource-name"/>
                </div>
              </template>
            </el-table-column>
            <el-table-column :fixed="!showMobilePage" align="left" label="账号ID" min-width="110">
              <template slot-scope="scope">
                <div v-for="(item,index) in scope.row.children" :style="rowStyle(item)" :key="index" :class="{'row-selected':isSelect(scope.row.ids, item.mediumId)}" class="merge-row-item">
                  <ToolTip :content="item.baseInfo.accountId" class="resource-name"/>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="left" label="下单平台" min-width="100">
              <template slot-scope="scope">
                <div v-for="(item,index) in scope.row.children" :key="index" :class="{'row-selected':isSelect(scope.row.ids, item.mediumId)}" class="merge-row-item">
                  <div :style="rowStyle(item)" class="flex-center ellipsisOne">
                    <platformIcon :class="{'gray-filter': item.status === 0}" :data="item.platformTypeName" />
                    {{ item.platformTypeName || '--' }}
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="left" label="所属经营体" min-width="130">
              <template slot-scope="scope">
                <div v-for="(item,index) in scope.row.children" :style="rowStyle(item)" :key="index" :class="{'row-selected':isSelect(scope.row.ids, item.mediumId)}" class="merge-row-item">
                  <ToolTip :content="item.attributionMatrixName" class="resource-name"/>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="left" label="协作部门" min-width="130">
              <template slot-scope="scope">
                <div v-for="(item,index) in scope.row.children" :style="rowStyle(item)" :key="index" :class="{'row-selected':isSelect(scope.row.ids, item.mediumId)}" class="merge-row-item">
                  <ToolTip :content="item.cooperationDepartmentNames" class="resource-name"/>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="left" label="链接" width="90">
              <template slot-scope="scope">
                <div v-for="(item,index) in scope.row.children" :key="index" :style="rowStyle(item)" :class="{'row-selected':isSelect(scope.row.ids, item.mediumId)}" class="merge-row-item">
                  <ToolTip :content="item.resourceLink">
                    <a
                      v-if="item.resourceLink.indexOf('http://') === 0 || item.resourceLink.indexOf('https://') === 0"
                      :href="item.resourceLink"
                      :style="rowStyle(item)"
                      target="_blank"
                      class="name link-name">
                      点击跳转<img :class="{'gray-filter': item.status === 0}" src="../../../assets/medium/link.png" alt="">
                    </a>
                    <div v-else :style="rowStyle(item)" class="resource-name ellipsisOne" style="max-width: 90px;">{{ item.resourceLink }}</div>
                  </ToolTip>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="left" label="运营模式" min-width="100">
              <template slot-scope="scope">
                <div v-for="(item,index) in scope.row.children" :style="rowStyle(item)" :key="index" :class="{'row-selected':isSelect(scope.row.ids, item.mediumId)}" class="merge-row-item">
                  <ToolTip :content="item.operateModeName" class="resource-name"/>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="left" label="合作运营方" min-width="120">
              <template slot-scope="scope">
                <div v-for="(item,index) in scope.row.children" :style="rowStyle(item)" :key="index" :class="{'row-selected':isSelect(scope.row.ids, item.mediumId)}" class="merge-row-item">
                  <ToolTip v-if="item.cooperation && item.cooperation.length > 5" :content="item.cooperation" class="resource-name"/>
                  <div v-else class="resource-name ellipsisOne" style="width: 110px;">{{ item.cooperation || '--' }}</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="left" label="所有人员" min-width="130">
              <template slot-scope="scope">
                <div
                  v-for="(item,index) in scope.row.children"
                  :style="rowStyle(item)"
                  :key="index"
                  :class="{'row-selected':isSelect(scope.row.ids, item.mediumId)}"
                  class="merge-row-item" >
                  <ToolTip v-if="item.accountOperationName && item.accountOperationName.length" :content="item.accountOperationName.join('/')" class="resource-name"/>
                  <div v-else>--</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="left" label="订单数" min-width="100">
              <template slot-scope="scope">
                <div v-for="(item,index) in scope.row.children" :style="rowStyle(item)" :key="index" :class="{'row-selected':isSelect(scope.row.ids, item.mediumId)}" class="merge-row-item">
                  {{ item.orderNum || '--' }}
                </div>
              </template>
            </el-table-column>
            <el-table-column align="left" label="有效" min-width="80">
              <template slot-scope="scope">
                <div v-for="(item,index) in scope.row.children" :style="rowStyle(item)" :key="index" :class="{'row-selected':isSelect(scope.row.ids, item.mediumId)}" class="merge-row-item">
                  {{ item.status ? '是' : '否' }}
                </div>
              </template>
            </el-table-column>
            <el-table-column align="left" label="是否挂靠" min-width="80">
              <template slot-scope="scope">
                <div v-for="(item,index) in scope.row.children" :style="rowStyle(item)" :key="index" :class="{'row-selected':isSelect(scope.row.ids, item.mediumId)}" class="merge-row-item">
                  {{ item.microTask ? '是' : '否' }}
                </div>
              </template>
            </el-table-column>
            <el-table-column align="left" label="系统ID" min-width="100">
              <template slot-scope="scope">
                <div v-for="(item,index) in scope.row.children" :style="rowStyle(item)" :key="index" :class="{'row-selected':isSelect(scope.row.ids, item.mediumId)}" class="merge-row-item">
                  {{ item.systemId || '--' }}
                </div>
              </template>
            </el-table-column>
            <el-table-column align="left" label="创建人" min-width="100">
              <template slot-scope="scope">
                <div v-for="(item,index) in scope.row.children" :style="rowStyle(item)" :key="index" :class="{'row-selected':isSelect(scope.row.ids, item.mediumId)}" class="merge-row-item">
                  {{ item.createName || '--' }}
                </div>
              </template>
            </el-table-column>
            <el-table-column align="left" label="创建时间" min-width="110">
              <template slot-scope="scope">
                <div v-for="(item,index) in scope.row.children" :style="rowStyle(item)" :key="index" :class="{'row-selected':isSelect(scope.row.ids, item.mediumId)}" class="merge-row-item">
                  <span v-if="item.createTime">{{ item.createTime | standardFormat('YYYY/MM/DD') }}</span>
                  <span v-else>--</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="left" label="更新人" min-width="90">
              <template slot-scope="scope">
                <div v-for="(item,index) in scope.row.children" :style="rowStyle(item)" :key="index" :class="{'row-selected':isSelect(scope.row.ids, item.mediumId)}" class="merge-row-item">
                  {{ item.updator || '--' }}
                </div>
              </template>
            </el-table-column>
            <el-table-column align="left" label="更新时间" min-width="110">
              <template slot-scope="scope">
                <div v-for="(item,index) in scope.row.children" :style="rowStyle(item)" :key="index" :class="{'row-selected':isSelect(scope.row.ids, item.mediumId)}" class="merge-row-item">
                  <span v-if="item.updateTime">{{ item.updateTime | standardFormat('YYYY/MM/DD') }}</span>
                  <span v-else>--</span>
                </div>
              </template>
            </el-table-column>
            <!-- <el-table-column align="left" :fixed="!showMobilePage"="right" label="" width="32">
              <template slot-scope="scope">
                <div v-for="(item,index) in scope.row.children" :key="index" style="border-color:transparent;" class="merge-row-item"/>
              </template>
            </el-table-column> -->
          </el-table>
        </div>
        <div style="display:flex;margin-top:10px;padding: 0 24px;">
          <div style="flex:1;display:flex;align-items:center;">
            <el-button :disabled="hasSelect" class="search-btn-style" type="primary" size="small" @click="mergePost">合并</el-button>
            <el-button class="cancel-btn-style" style="margin-left: 16px;" type="info" size="small" @click="handleClose">取消</el-button>
          </div>
          <el-pagination
            v-if=" mergeData && mergeData.total > 0"
            :current-page="mergeData.page "
            :page-size="mergeData.perPage"
            :total="mergeData.total"
            :page-sizes="[10, 20, 50, 100, 250, 500]"
            :layout="showMobilePage?'prev, next':'prev, pager, next,sizes, jumper'"
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </div>
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="mergeDialog"
      :before-close="mergeDialogClose"
      :append-to-body="false"
      :modal-append-to-body="false"
      :class="{'mobile-el-dialog': showMobilePage}"
      class="merge-post-dialog"
      width="450px">
      <div v-loading="mergeLoading">
        <div>
          <Title title="资源同步更新选择" font-size="16px" />
        </div>
        <div class="tip" style="margin-bottom: 20px;">
          执行合并将同步更新合并后的资源到以下关联项，且合并资源
          与同步后无法恢复，请谨慎操作!
        </div>
        <div style="margin-bottom: 10px;"><el-checkbox v-model="relationDate" disabled>预约</el-checkbox></div>
        <div style="margin-bottom: 10px;"><el-checkbox v-model="relationMediumOrder" disabled>询单</el-checkbox></div>
        <div style="margin-bottom: 10px;"><el-checkbox v-model="relationOrder">订单（注：已封账订单不会进行更新）</el-checkbox></div>
        <div v-if="relationOrder" class="time-select">
          <span class="label">订单创建时间</span>
          <el-date-picker
            v-model="timeRange"
            type="daterange"
            size="small"
            value-format="timestamp"
            format="yyyy/MM/dd"
            start-placeholder="开始日期"
            end-placeholder="结束日期"/>
        </div>
        <div style="margin-top: 30px;display:flex;">
          <div style="flex:1;"/>
          <el-button class="search-btn-style" type="primary" size="small" plain @click="mergeStart">确认合并</el-button>
          <el-button class="cancel-btn-style" type="info" size="small" @click="mergeDialogClose">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Title from '@/components/Title';
import { getMergeList, merge } from '@/api/resource';
import { standardFormat } from '@/filters/date';
import platformIcon from '@/components/Common/platformIcon';
import ElMessage from '@/utils/message';
import { mapState } from 'vuex';
export default {
  components: { Title, platformIcon },
  filters: { standardFormat, microTaskFilter(task) {
    if (!task && task !== 0) return '--';
    const taksArr = ['否', '是'];
    return taksArr[task];
  } },
  data() {
    return {
      timeRange: [],
      overFlowStyle: {
        textOverflow: 'ellipsis',
        overflow: 'hidden',
        wordBreak: 'break-all',
        whiteSpace: 'nowrap'
      },
      dialogVisible: false,
      mergeDialog: false,
      filedName: 'resourceName',
      loading: false,
      mergeLoading: false,
      selectIds: [],
      page: 1,
      perPage: 10,
      relationMediumOrder: true,
      relationDate: true,
      relationOrder: false,
      mergeData: {},
      platformType: '',
      keyword: '',
      keyOption: [
        { label: '账号', value: 'resourceName' },
        { label: '账号ID', value: 'accountId' },
        { label: '账号归属', value: 'accountBelongName' },
        { label: '所属经营体', value: 'attributionMatrixName' },
        { label: '所属机构', value: 'organization' },
        { label: '所有人员', value: 'accountOperationName' }
      ],
      mergeParamsData: []
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    hasSelect() {
      let flag = false;
      const arr = this.mergeData.items || [];
      arr.forEach(i => {
        if (i.ids.length > 0) {
          flag = true;
        }
      });
      return !flag;
    }
  },
  methods: {
    async getData(reset = false) {
      if (reset) this.page = 1;
      try {
        const params = {
          page: this.page,
          perPage: this.perPage,
          keyword: this.keyword,
          platformType: this.platformType,
          filedName: this.filedName
        };
        this.loading = true;
        const res = await getMergeList(params);
        this.loading = false;
        if (res.code === 200 && res.data) {
          res.data.items.forEach(i => {
            i.mainId = '';
            i.ids = [];
            if (i.children) {
              i.children.forEach(j => {
                j.isSelect = false;
                if (j.accountOperation && j.accountOperation.length > 0) {
                  j.accountOperationName = j.accountOperation.map(k => k.value);
                }
                if (j.cooperationDepartment && j.cooperationDepartment.length > 0) {
                  j.cooperationDepartmentNames = j.cooperationDepartment.map(j => j.value).join('/');
                }
              });
            }
          });
          this.mergeData = res.data;
        } else {
          this.$message.error(res.message);
        }
      } catch (error) {
        this.loading = false;
        console.log(error);
      }
    },
    selectItem(ids, parentItem) {
      if (!ids.includes(parentItem.mainId) || parentItem.ids.length <= 1) parentItem.mainId = '';
    },
    isSelect(ids, id) {
      if (!ids) return false;
      return ids.includes(id);
    },
    mergePost() {
      const mergeIds = [];
      this.mergeData.items.forEach(i => {
        if (i.mainId && i.ids.length >= 2) {
          mergeIds.push({
            mainId: i.mainId,
            ids: i.ids
          });
        }
      });
      if (mergeIds.length === 0) {
        ElMessage.warning('请选择需要合并的资源和合并源');
        return;
      }
      this.mergeParamsData = mergeIds;
      this.mergeDialog = true;
    },
    mergeStart() {
      const mergeParamsData = JSON.parse(JSON.stringify(this.mergeParamsData));
      mergeParamsData.forEach(i => {
        i.ids = i.ids.filter(j => {
          return j !== i.mainId;
        });
      });
      const params = {
        mergeIds: mergeParamsData,
        relationOrder: this.relationOrder,
        relationDate: this.relationDate,
        relationMediumOrder: this.relationMediumOrder
      };
      if (this.relationOrder) {
        if (this.timeRange.length !== 2) {
          ElMessage.warning('请选择订单创建时间');
          return;
        }
        params.start = this.timeRange[0];
        params.end = this.timeRange[1];
      }
      this.mergeLoading = true;
      merge(params).then(res => {
        this.mergeLoading = false;
        if (res.code === 200) {
          ElMessage.success('合并成功');
          this.$emit('freshData');
          this.mergeDialogClose();
          this.handleClose();
        } else {
          ElMessage.error(res.message);
        }
      }).catch(() => {
        this.mergeLoading = false;
      });
    },
    dialogShow(plateform) {
      this.platformType = plateform;
      this.dialogVisible = true;
      this.getData(true);
    },
    handleClose() {
      this.dialogVisible = false;
      this.relationOrder = false;
      this.mergeParamsData = [];
    },
    mergeDialogClose() {
      this.mergeDialog = false;
    },
    handleSizeChange(size) {
      this.perPage = size;
      this.getData(true);
    },
    handleCurrentChange(page) {
      this.page = page;
      this.getData();
    },
    rowStyle(item) {
      if (item.status === 0) {
        return { color: '#999 !important' };
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.merge-resource-dialog {
  &::v-deep {
    .el-dialog {
      border-radius: 8px;
      overflow: hidden;
      .el-dialog__header {
        display: none;
      }
    }
    .el-dialog__body {
      padding: 19px 0px 8px;
      border-radius: 0px 0px 16px 16px;
    }
  }
}
.dialog-scroll {
  @include scrollBar($x: hidden, $y: auto);
}
.right-tip{
  margin-left: 8px;
  font-size: 12px;
}
.merge-post-dialog {
  &::v-deep {
    .el-dialog__body {
      padding-top: 2px;
    }
  }
}
.merge-input {
  width: 341px;
  &::v-deep {
    .el-input__inner {
      height: 30px;
      border-radius: 0;
      background-color: #FAFAFC;
    }
    .el-input-group__prepend {
      background-color: #fff;
      .el-input__inner {
        width: 90px !important;
        padding-right: 0px;
      }
    }
    .changeStatus {
      display: flex;
      align-items: center;
      .el-input__suffix {
        display: flex;
        align-items: center;
        right: 0;
      }
      .el-input__inner {
        color: #333 !important;
      }
    }
  }
}
.merge-header {
  display: flex;
  padding: 0 24px;
  align-items: center;
  margin-bottom: 10px;
  &.is-mobile {
    flex-wrap: wrap;
    .merge-input {
      width: 100% !important;
    }
  }
}
.mt10 {
  margin-top: 10px;
}
.merge-row-item {
  height: 56px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #eee;
  padding-left: 10px;
  padding-right: 10px;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  width: 100%;
  .content {
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
    width: 100%;
  }
  // &.select {
  //   background: #e9f5fa;
  // }
  & ::v-deep {
    .resource-name {
      text-overflow: ellipsis;
      overflow: hidden;
      word-break: break-all;
      white-space: nowrap;
      width: 100%;
    }
    .el-radio__label {
      display: none;
    }
    .el-checkbox__label {
      display: none;
    }
  }
}
.row-selected {
  background: #F3F5FB;
}
.merge-btn {
  cursor: pointer;
  color: #406eff;
}
.merge-table {
  padding: 0 24px;
  .gray-filter {
    filter: grayscale(100%);
    color: #ddd;
    opacity: 0.2;
  }
  &::v-deep {

    .el-table__fixed-right {
      box-shadow: none !important;
    }
    .merge-table-row {
      background: #f5f5f5;
      & > td {
        padding: 0;
        padding-bottom: 2px;
        background: #f5f5f5 !important;
        border-bottom: 2px solid #f5f5f5 !important;
        .merge-row-item {
          position: relative;
          &:last-child {
            border-bottom: 2px solid #f5f5f5 !important;
          }
        }
      }
      .cell {
        padding: 0;
        background-color: #fff !important;
      }
      &:last-child {
        & > td {
          padding-bottom: 0;
          border-bottom: none !important;
          .merge-row-item {
            &:last-child {
              border-bottom: none !important;
            }
          }
        }
      }
    }
    .invalid-class {
      .cell,.resource-name {
        color: #999 !important;
      }
    }
    .merge-table-row:hover{
        background: #F3F5FB!important;
    }
    .el-table__fixed {
      height: 100% !important;
    }
  }
}

.link-name {
  display: flex;
  align-items:center;
  color: #406eff;
  img {
    position: relative;
    top: 1px;
    width: 11px;
    margin-left: 3px;
  }
  .el-icon-link {
    font-size: 12px;
  }
}
.tip {
  color: rgb(233, 20, 20);
  margin: 10px 0 0px 0;
  padding: 0 32px;
}
.search-btn{
  border-radius: 0px 4px 4px 0px;
}
.time-select {
  .label {
    font-size: 14px;
    margin-left: 23px;
    margin-right: 5px;
  }
  & ::v-deep {
    .el-range-editor--small {
      &.el-input__inner {
        height: 30px;
        width: 240px;
        &:hover {
          border-color: #406EFF;
        }
      }
      .el-range-input {
        font-size: 13px;
      }
      .el-range__close-icon {
        width: 14px;
      }
      .el-range-separator{
        line-height: 22px;
        padding: 0;
        width: 8%;
        box-sizing: content-box;
      }

    }
  }
}
</style>
